'use strict';

const db = uniCloud.database();
const collection = db.collection('food-dishes');

exports.main = async (event, context) => {
  const { dishIds } = event.data || {};
  
  if (!dishIds || !Array.isArray(dishIds) || dishIds.length === 0) {
    return {
      code: 400,
      message: '缺少菜品ID列表',
      data: null
    };
  }
  
  try {
    // 查询指定菜品的材料信息
    const result = await collection
      .where({
        _id: db.command.in(dishIds)
      })
      .field({
        _id: true,
        name: true,
        ingredients: true
      })
      .get();
    
    if (!result.data || result.data.length === 0) {
      return {
        code: 404,
        message: '菜品不存在',
        data: []
      };
    }
    
    // 构建材料数据，以菜品ID为键
    const materialsMap = {};
    result.data.forEach(dish => {
      materialsMap[dish._id] = {
        _id: dish._id,
        name: dish.name,
        ingredients: dish.ingredients || {
          main_ingredients: '',
          auxiliary_ingredients: '',
          seasonings: ''
        }
      };
    });
    
    return {
      code: 200,
      message: '查询成功',
      data: materialsMap
    };
  } catch (error) {
    console.error('查询菜品材料出错:', error);
    return {
      code: 500,
      message: '查询失败',
      data: null
    };
  }
};
